import React, { Component } from 'react';
import { routerRedux, Route, Switch, Link } from 'dva/router';
import Debounce from 'lodash-decorators/debounce';
import Bind from 'lodash-decorators/bind';
import { connect } from 'dva';
import {
  Button,
  Menu,
  Dropdown,
  Icon,
  Row,
  Col,
  Input,
  InputNumber,
  Steps,
  Card,
  Popover,
  Badge,
  Table,
  Tooltip,
  Divider,
  Checkbox,
  Modal,
  Radio,
  Select,
  message,
  TreeSelect,
  Form,
  Upload,
  Spin,
  DatePicker,
} from 'antd';
import moment from 'moment';
import classNames from 'classnames';
import { getRoutes } from '../../../utils/utils';
import PageHeaderLayout from '../../../layouts/PageHeaderLayout';
import ImageUploader from '../../../components/Falcon/Attachment/ImageUploader';
import DescriptionList from '../../../components/DescriptionList';
import styles from './style.less';
import { create } from 'domain';
import { solo } from '../../../common/solo';
import querystring from 'querystring';
import { bind } from 'lodash-decorators/utils';

const { Step } = Steps;
const { Description } = DescriptionList;
const ButtonGroup = Button.Group;
const RadioGroup = Radio.Group;
const Option = Select.Option;
const TreeNode = TreeSelect.TreeNode;
const FormItem = Form.Item;
const { TextArea } = Input;

const formItemLayout = {
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 16,
  },
};

@connect(({ system }) => ({
  system,
}))
@Form.create()
export default class Step1 extends Component {
  state = {
    id: '',
    structureId: '',
    type: '',
    dealerLevel: false,
    branchIdList: null,
    isFileListLoading: false,
    stateStructure: '',
    organizationBasic: {},
    fileList: {
      license: [],
    },
  };

  componentDidMount() {
    const {
      system: { structureId, stateStructure, systemBranchId, systemDetailValue },
    } = this.props;
    const { dispatch, location } = this.props;
    const params = querystring.parse(location.search.slice(1));
    if (systemDetailValue) {
      if (params.stateStructure == 6) {
        dispatch({
          type: 'system/detailsStructure',
          payload: {
            id: params.id,
          },
          callback: () => {
            const { system: { structureBranchList } } = this.props;
            const { branch } = structureBranchList;
            let fileList = this.state.fileList;
            fileList.license.splice(0, fileList.license.length); //设置数据前先清空里面的东西
            this.setState({ isFileListLoading: true });
            if (branch && branch.license) {
              fileList.license.push({
                uid: branch.license,
                key: branch.license,
                name: branch.license,
                status: 'done',
                url: solo.imgShow + branch.license,
              });
            }
            this.setState({ fileList });
          },
        });
      }
    }
    dispatch({
      type: 'system/fetchBasic',
    });

    this.setState({
      id: structureId,
      type: params.type,
      stateStructure: params.stateStructure,
      structureId: params.id,
    });
    if (params.type == 2) {
      const { system: { systemDetailValue } } = this.props;
      if (systemDetailValue) {
        const { fileList } = systemDetailValue;
        this.setState({
          organizationBasic: systemDetailValue,
          fileList,
        });
      }
    }
  }

  nextStep = () => {
    const { dispatch } = this.props;
    const { validateFieldsAndScroll } = this.props.form;
    validateFieldsAndScroll((error, values) => {
      if (!error) {
        if (values.orgName && values.parentId) {
          dispatch({
            type: 'system/setSystemlValue',
            payload: {
              ...values,
              fileList: this.state.fileList,
              license:
                this.state.fileList.license.length > 0 ? this.state.fileList.license[0].key : null,
            },
          });
          dispatch(
            routerRedux.push(
              `/system/system-form/credits?branchId=${values.parentId}&stateStructure=${
                this.state.stateStructure
              }&id=${this.state.id && this.state.id}`
            )
          );
        } else {
          message.warning('请先填写基本信息');
        }
      }
    });
    // console.log('this.formRef=', this.formRef);
  };

  handleSelectCustomerClick = () => {
    this.setState({
      dealerLevel: true,
    });
  };

  handleCancelDealerLevel = () => {
    this.setState({
      dealerLevel: false,
    });
  };

  handleBranchIdList = value => {
    this.setState({
      branchIdList: value,
    });
  };

  renderTreeNodesChildren = data => {
    return data.map(item => {
      if (item.children) {
        return (
          <TreeNode value={item.id} title={item.orgName} key={item.id} dataRef={item}>
            {this.renderTreeNodesChildren(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode value={item.id} key={item.id} dataRef={item} title={item.orgName} />;
    });
  };

  handleImageUploaded = (fieldName, fileList) => {
    switch (fieldName) {
      case '营业执照':
        this.setState({
          fileList: { ...this.state.fileList, license: fileList },
        });
        break;
    }
  };

  render() {
    const { system: { branchTreeList, structureBranchList, streuctureLoading } } = this.props;
    const { type, organizationBasic, stateStructure, isFileListLoading } = this.state;
    const { getFieldDecorator } = this.props.form;
    return (
      <Row>
        {stateStructure == 6 && !isFileListLoading ? (
          <div className={styles.spinContainer}>
            <Spin size="large" />
          </div>
        ) : (
          <Form className={styles.stepForm}>
            <div>
              <Row style={{ textAlign: 'centent' }}>
                <Col span={12}>
                  <FormItem label="组织名称" {...formItemLayout}>
                    {getFieldDecorator('orgName', {
                      rules: [
                        {
                          required: true,
                          message: '请输入组织名称',
                        },
                      ],
                      initialValue:
                        stateStructure == 6
                          ? structureBranchList.branch && structureBranchList.branch.orgName
                          : organizationBasic && organizationBasic.orgName,
                    })(<Input placeholder="请输入组织名称" />)}
                  </FormItem>
                </Col>
                <Col span={12}>
                  <FormItem label="上级组织" {...formItemLayout}>
                    {getFieldDecorator('parentId', {
                      rules: [
                        {
                          required: true,
                          message: '请选择上级组织',
                        },
                      ],
                      initialValue:
                        stateStructure == 6
                          ? structureBranchList.branch && structureBranchList.branch.parentId
                          : organizationBasic && organizationBasic.parentId,
                    })(
                      <TreeSelect
                        dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                        placeholder="请选择"
                        allowClear
                        treeDefaultExpandAll
                        onChange={this.handleBranchIdList}
                      >
                        {branchTreeList && this.renderTreeNodesChildren(branchTreeList)}
                      </TreeSelect>
                    )}
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={12}>
                  <FormItem label="负责人" {...formItemLayout}>
                    {getFieldDecorator('leader', {
                      initialValue:
                        stateStructure == 6
                          ? structureBranchList.branch && structureBranchList.branch.leader
                          : organizationBasic && organizationBasic.leader,
                    })(<Input placeholder="请输入负责人" />)}
                  </FormItem>
                </Col>

                <Col span={12}>
                  <FormItem label="联系方式" {...formItemLayout}>
                    {getFieldDecorator('phone', {
                      initialValue:
                        stateStructure == 6
                          ? structureBranchList.branch && structureBranchList.branch.phone
                          : organizationBasic && organizationBasic.phone,
                    })(<Input placeholder="请输入联系方式" />)}
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={12}>
                  <FormItem label="开户银行" {...formItemLayout}>
                    {getFieldDecorator('depositBank', {
                      initialValue:
                        stateStructure == 6
                          ? structureBranchList.branch && structureBranchList.branch.depositBank
                          : organizationBasic && organizationBasic.depositBank,
                    })(<Input placeholder="请输入开户银行" />)}
                  </FormItem>
                </Col>
                <Col span={12}>
                  <FormItem label="银行账号" {...formItemLayout}>
                    {getFieldDecorator('bankAccount', {
                      initialValue:
                        stateStructure == 6
                          ? structureBranchList.branch && structureBranchList.branch.bankAccount
                          : organizationBasic && organizationBasic.bankAccount,
                    })(<Input placeholder="请输入银行账号" />)}
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={12}>
                  <FormItem label="组织地址" {...formItemLayout}>
                    {getFieldDecorator('regAddress', {
                      initialValue:
                        stateStructure == 6
                          ? structureBranchList.branch && structureBranchList.branch.regAddress
                          : organizationBasic && organizationBasic.regAddress,
                    })(<Input placeholder="请输入组织地址" />)}
                  </FormItem>
                </Col>
                <Col span={12}>
                  <FormItem label="营业执照号" {...formItemLayout}>
                    {getFieldDecorator('licenseNo', {
                      initialValue:
                        stateStructure == 6
                          ? structureBranchList.branch && structureBranchList.branch.licenseNo
                          : organizationBasic && organizationBasic.licenseNo,
                    })(<Input placeholder="请输入营业执照号" />)}
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={12}>
                  <FormItem {...formItemLayout} label="备注">
                    {getFieldDecorator('remark', {
                      initialValue:
                        stateStructure == 6
                          ? structureBranchList.branch && structureBranchList.branch.remark
                          : organizationBasic && organizationBasic.remark,
                    })(<TextArea placeholder="请输入备注" rows={4} />)}
                  </FormItem>
                </Col>
                <Col span={12}>
                  <FormItem label="营业执照" {...formItemLayout}>
                    <ImageUploader
                      fieldName="营业执照"
                      label="营业执照"
                      maxCount={1}
                      size="large"
                      showRemoveIconType={true}
                      attachmentData={{
                        projectId: '', //业务ID
                        customerId: '', //客户ID
                        attachType: '0', //0：图片；1：视频
                        attachKind: '', //附件种类
                        type: '营业执照', //图片类型
                      }}
                      fileList={this.state.fileList.license}
                      onImageUploaded={this.handleImageUploaded}
                    />
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={24} style={{ marginLeft: '20%' }}>
                  <FormItem
                    wrapperCol={{
                      xs: { span: 24, offset: 0 },
                      sm: {
                        span: formItemLayout.wrapperCol.span,
                        offset: formItemLayout.labelCol.span,
                      },
                    }}
                    label=""
                  >
                    <Button type="primary" onClick={this.nextStep}>
                      下一步
                    </Button>
                  </FormItem>
                </Col>
              </Row>
            </div>
          </Form>
        )}
      </Row>
    );
  }
}
